<template>
    <div style="height:100%">
        <div class="base-info" v-if="detail.title">
            <div class="cover">
                <img v-if="detail.cover" :src="imgSiteUrl+detail.cover" alt="">
                <img v-else src="@/assets/album-cover.png" alt="">
            </div>
            <h2>{{detail.title}}</h2>
            <div class="ctrls">
                {{total}}张/
                <a-button type="primary" @click="editVisible=true">
                    <upload-outlined></upload-outlined>
                    添加图片
                </a-button>
                <a-button type="primary" ghost v-if="total>0&&!manageStatus" @click="manageStatus=true">管理</a-button>
                <a-button type="primary" ghost v-if="manageStatus" @click="cancelManage">取消</a-button>
                <a-button type="primary" v-if="manageStatus" @click="deleteImg">删除</a-button>
            </div>
            <p>{{detail.desc}}</p>
        </div>
        <div class="list-blank" v-if="list.length===0">
            <a-empty description="暂无图片" />
        </div>
        <div class="list">
            <ul>
                <li v-for="item in list" :key="item.id">
                    <img :src="imgSiteUrl+item.thumb" :alt="item.title" :title="item.title" @click="previewImg(item,true)">
                    <div class="select-btn" :class="{'checked':selectedIds.indexOf(item.id)!==-1}" @click="selectItem(item.id)" v-if="manageStatus">
                        <check-circle-filled />
                    </div>
                    <a-dropdown :trigger="['click']" placement="bottomRight">
                        <div class="setting-btn">
                            <down-square-filled />
                        </div>
                        <template #overlay>
                            <a-menu>
                                <a-menu-item key="0" @click="editInfo(item)">
                                    <edit-outlined />编辑
                                </a-menu-item>
                                <a-menu-item key="1" @click="deleteImgItem(item.id)">
                                    <delete-outlined />删除
                                </a-menu-item>
                            </a-menu>
                        </template>
                    </a-dropdown>
                </li>
            </ul>
            <div class="clear"></div>
        </div>
    </div>


    <a-modal v-model:visible="editVisible" title="上传图片" @ok="handleAdd" @cancel="cancelEdit" :centered="true" :width="500" class="edit-photo-album">
        <a-row>
            <a-col :span="4" class="label-name">标题</a-col>
            <a-col :span="20">
                <a-input v-model:value="formState.name" />
            </a-col>
        </a-row>
        
        <div class="blank"></div>
        <a-row>
            <a-col :span="4" class="label-name">图片</a-col>
            <a-col :span="20">
                <a-upload list-type="picture-card" action="n" :show-upload-list="false" @change="handlePreview" :before-upload="handleChangeBanner" accept=".png,.jpg">
                    <div v-if="formState.coverPreview===''" class="cover">
                        <img src="@/assets/album-cover.png" alt="" />
                        <div class="text">选择图片</div>
                    </div>
                    <div v-else class="cover">
                        <img :src="formState.coverPreview" alt="" style="width:265px;height:138px" />
                    </div>
                </a-upload>
            </a-col>
        </a-row>

        <div class="blank"></div>
        <a-row>
            <a-col :span="4" class="label-name">描述</a-col>
            <a-col :span="20">
                <a-textarea v-model:value="formState.desc" />
            </a-col>
        </a-row>
    </a-modal>

    <a-modal v-model:visible="editVisible2" title="编辑图片信息" @ok="handleEdit" @cancel="cancelEdit" :centered="true" :width="500" class="edit-photo-album">
        <a-row>
            <a-col :span="4" class="label-name">标题</a-col>
            <a-col :span="20">
                <a-input v-model:value="formState.name" />
            </a-col>
        </a-row>

        <div class="blank"></div>
        <a-row>
            <a-col :span="4" class="label-name">描述</a-col>
            <a-col :span="20">
                <a-textarea v-model:value="formState.desc" />
            </a-col>
        </a-row>
    </a-modal>
    
    <div class="big-preview-wrap" v-show="previewVisible" @click="hidePreview">
        <div class="big-preview" @click.stop>
            <div class="pic">
                <div class="big-img">
                    <img v-if="previewInfo.path" :src="imgSiteUrl+previewInfo.path" alt="">
                </div>
                <div class="thumbs">
                    <left-circle-outlined @click="moveleft" />
                    <right-circle-outlined @click="moveRight" />
                    <div class="thumb-inner">
                        <div class="thumb-list" ref="thumbs" :style="{marginLeft:'-'+moveoutLength+'px'}">
                            <div class="thumb-item" v-for="item in list" :key="item.id" :class="{active:item.id===previewInfo.id}">
                                <img :src="imgSiteUrl+item.thumb" alt="" @click="previewImg(item,false)">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="info">
                <h2>{{previewInfo.title}}</h2>
                <p>{{previewInfo.desc}}</p>
                <div class="date">上传时间：{{previewInfo.addtime}}</div>
                <div class="date">修改时间：{{previewInfo.updatetime}}</div>
            </div>
        </div>
    </div>
</template>

<script>
import Http from "@/until/http";
import { useRoute } from "vue-router";
import { defineComponent, onMounted, reactive, ref, toRefs,createVNode } from "vue";
import { 
    UploadOutlined,
    CheckCircleFilled,
    QuestionCircleOutlined,
    DownSquareFilled,
    DeleteOutlined,
    EditOutlined,
    LeftCircleOutlined,
    RightCircleOutlined 
} from '@ant-design/icons-vue';
import reqwest from 'reqwest';
import config from "@/until/configs";
import { messageTips } from "@/until/tools";
import { Modal } from "ant-design-vue/lib";
function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
export default defineComponent({
    components:{
        UploadOutlined,
        CheckCircleFilled,
        QuestionCircleOutlined,
        DownSquareFilled,
        DeleteOutlined,
        EditOutlined,
        LeftCircleOutlined,
        RightCircleOutlined
    },
    setup() {
        const route = useRoute();
        const albumId = route.query.id;
        const thumbs = ref(null);
        const state = reactive({
            detail:{},
            list:[],
            total:0,
            imgSiteUrl:config.imgSiteUrl,
            editVisible:false,
            editVisible2:false,
            selectedIds:[],
            manageStatus:false,
            previewVisible:false,
            previewInfo:{}, 
            moveoutLength:0           
        })

        let thumbsWidth=0;

        const formState = reactive({
            name:'',
            desc:'',
            coverPreview:'',
            coverUrl:''
        })


        const handleAdd = ()=>{
            const formData = new FormData();
            if(!formState.coverUrl) {
                messageTips('请选择图片',2);
                return false;
            }
            formData.append('file', formState.coverUrl);
            formData.append('name', formState.name?formState.name:formState.coverUrl.name);
            formData.append('desc', formState.desc);
            formData.append('fid', albumId);
            let path =  config.baseUrl+'/admin/elegant/addPicToAlbum';
            reqwest({
                url: path,
                method: 'post',
                processData: false,
                data: formData,
                contentType : false,
                success: (res) => {
                    try{
                        let result = JSON.parse(res);
                        if(result.success) {
                            messageTips(result.message,3);
                            state.editVisible = false;
                            cancelEdit();
                            getList();
                        }
                    }catch(e) {
                        console.log(e)
                    }
                },
                error: (e) => {
                    if(e.status===401) {
                        messageTips('登录已过期',1);
                        setTimeout(()=>{
                            location.href = '/login';
                        },2000);
                    } 
                },
            });
        }

        const cancelEdit = ()=>{
            Object.assign(formState,{
                id:null,
                name:'',
                desc:'',
                coverPreview:'',
                coverUrl:''
            });
            Object.assign(state,{
                editVisible:false,
                editVisible2:false
            });
        }

        const handlePreview= async ({file})=>{
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            formState.coverPreview = file.url || file.preview;
        }

        const handleChangeBanner=(info)=>{
            formState.coverUrl = info;
        }

        const getList = ()=>{
            Http.getAlbumPics({id:albumId}).then(res=>{
                if(res) {
                    if(res.success) {
                        Object.assign(state,{
                            detail:res.detail,
                            list:res.list,
                            total:res.count
                        })
                    }

                }
            });
        }

        const selectItem = (id)=>{
            let arr = [...state.selectedIds];
            let index = arr.indexOf(id);
            if(index===-1) {
                arr.push(id);
            } else {
                arr.splice(index,1);
            }
            Object.assign(state,{
                selectedIds:arr
            })
        }

        const cancelManage = ()=>{
            Object.assign(state,{
                selectedIds:[],
                manageStatus:false
            })
        }

        const deleteImg = ()=>{
            if(state.selectedIds.length===0) {
                messageTips('请选择图片',2);
                return false;
            }

            Modal.confirm({
                title:'提示',
                icon: createVNode(QuestionCircleOutlined),
                content:'您确定要删除这'+state.selectedIds.length+'张图片吗？',
                centered:true,
                okText:'确定',
                cancelText:'取消',
                onOk() {
                    Http.deleteAlbumImg({ids:state.selectedIds.join(',')}).then(res=>{
                        if(res) {
                            if(res.success) {
                                messageTips(res.message,3);
                                Object.assign(state,{
                                    manageStatus:false,
                                    selectedIds:[]
                                });
                                getList();
                            } else {
                                messageTips(res.message,1);
                            }
                        }
                    })
                }
            })
        }

        const deleteImgItem = (id)=>{
            Modal.confirm({
                title:'提示',
                icon: createVNode(QuestionCircleOutlined),
                content:'您确定要删除这张图片吗？',
                centered:true,
                okText:'确定',
                cancelText:'取消',
                onOk() {
                    Http.deleteAlbumImg({ids:id}).then(res=>{
                        if(res) {
                            if(res.success) {
                                messageTips(res.message,3);
                                Object.assign(state,{
                                    manageStatus:false,
                                    selectedIds:[]
                                })
                                getList();
                            } else {
                                messageTips(res.message,1);
                            }
                        }
                    })
                }
            })
        }

        const editInfo=(item)=>{
            Object.assign(formState,{
                id:item.id,
                name:item.title,
                desc:item.desc
            })
            Object.assign(state,{
                editVisible2:true
            })
        }

        const handleEdit=()=>{

            Http.editAlbumImgInfo({name:formState.name,id:formState.id,desc:formState.desc}).then(res=>{
                if(res) {
                    if(res.success) {
                        messageTips(res.message,3);
                        cancelEdit();
                        getList();
                    } else {
                        messageTips(res.message,1);
                    }
                }
            })
        }

        const previewImg=(item,flag)=>{
            Object.assign(state,{
                previewVisible:true,
                previewInfo:item
            });

            if(flag) {
                setTimeout(()=>{
                    let length = thumbs.value.children.length;
                    let total = 0;
                    for(let i=0; i<length; i++) {
                        let width = parseInt(window.getComputedStyle(thumbs.value.children[i]).width);
                        total+=width;
                    }
                    thumbsWidth = total+length*10;
                    Object.assign(state,{
                        moveoutLength:0
                    })
                },100);
            }
        }

        const moveleft=()=>{
            if(state.moveoutLength>0) {
                if(state.moveoutLength-100>0) {
                    Object.assign(state,{
                        moveoutLength:state.moveoutLength-100
                    });
                } else {
                    Object.assign(state,{
                        moveoutLength:0
                    });
                }
            }
        }

        const moveRight=()=>{
            if(thumbsWidth>state.moveoutLength+780) {
                if(thumbsWidth<state.moveoutLength+880) {
                    Object.assign(state,{
                        moveoutLength:thumbsWidth-780
                    });
                } else {
                    Object.assign(state,{
                        moveoutLength:state.moveoutLength+100
                    });
                }
            } else {
                Object.assign(state,{
                    moveoutLength:thumbsWidth-780
                });
            }
        }

        const hidePreview=()=>{
            Object.assign(state,{
                previewVisible:false,
                previewInfo:{}
            });
        }

        onMounted(()=>{
            getList();
        })

        return {
            ...toRefs(state),
            formState,
            handleAdd,
            handlePreview,
            handleChangeBanner,
            cancelEdit,
            selectItem,
            cancelManage,
            deleteImg,
            deleteImgItem,
            handleEdit,
            editInfo,
            previewImg,
            thumbs,
            hidePreview,
            moveleft,
            moveRight
        }
    }
})
</script>

<style lang="scss" scoped>
@import '@/scss/album_detail.scss';
</style>